Implementing User Authentication
Jeffrey Bardzell
www.allectomedia.com
ittraining.iu.edu
This article covers just a small portion of the Dreamweaver MX 2004: Website Development instructor-led course. If you like what you see and want to get the full experience, find a Macromedia Authorized Training Partner near you. Only at a Macromedia Authorized Training location will you learn from instructors thoroughly trained and certified by Macromedia.
Or if you prefer to learn on your own, check out Macromedia Dreamweaver MX 2004 with ASP, ColdFusion, and PHP: Training From the Source (Macromedia Press), by Jeffrey Bardzell.
Note: ASP.NET users can learn how to implement user authentication with Heidi Baustista’s Implementing Form-Based Authentication article.
Implementing a framework that allows users to register and log in is one of the most common tasks for web developers. Pages in the site are divided into those that are publicly accessible and those that require users to log in. A set of registration and log-in pages allow users to get through the barriers and access pages requiring authentication. Creating a user authentication framework is the centerpiece of this tutorial. Thanks to a series of Dreamweaver server behaviors, creating an authentication framework is much easier than you might think.
In this tutorial, you'll create a complete registration and log-on system, taking into account both when things go right and when they go awry (for example, log-on fails or a username is already in use). You will work on eight pages, five of which are specifically related to registration and log-on, two of which are protected, and the last one is simply an index page. Once you have a system like this set up, you can add as many restricted pages as you like. You can even implement roles-based authorization, in which users can access only certain pages in the site, even after they have logged in.
Requirements
To complete this tutorial you must fulfill the following prerequisites and install software and sample files:
-
Dreamweaver MX 2004
-
You are comfortable with Dreamweaver and its interface
- You have access to a web server capable of running ASP, ColdFusion, or PHP pages
- You have the knowledge and permission to configure a dynamic site, including creating your own data sources and the configuration of the included site files
- You have learned basic concepts and techniques for developing ASP, ColdFusion, or PHP pages (though you certainly need not be an expert in one of these areas)
-
Tutorials and sample files:
user_auth_start.zip (308K
ZIP)
Setting Up The Site
Before you can complete the tutorial, download and configure the site files on the first page of this article. Install the files on a web server (Dreamweaver calls this the Testing Server). This server can be a locally running copy of IIS (for ASP, ColdFusion, or PHP), the ColdFusion standalone web server, or Apache (for PHP). PHP users will also need access to a MySQL server. The following basic directions summarize the setup procedures.
- Unzip the files and copy them onto the server.
- ASP and ColdFusion users: Put users.mdb Access database in a folder with appropriate permissions on it, so that the web user has Full Control over it (Windows XP users can put it in the Shared Documents folder). Create a DSN that specifies the Access database. Although the name of the DSN doesn't strictly matter, the steps and screen shots assume the DSN is named user_auth. To learn how to set up a DSN, see Setting up a DSN in Windows (TechNote 15912).
- PHP users: Process users.sql to create and populate a database inside your MySQL database server.
- Define a new site in Dreamweaver that points to these files. Be sure to specify a server model and a Testing Server, including the URL Prefix. For help on learning how to define a site in Dreamweaver, see How to define a site in Dreamweaver (TechNote 14028).
- Create a database connection in Dreamweaver, using the Databases panel. Though the connection name doesn't matter, the steps and screen shots for this tutorial use user_auth as the name. See the documentation within Dreamweaver for information on how to set up a database connection by selecting Window > Using Dreamweaver > Index tab > connecting to databases.
User Authentication as a Web Application
Before jumping in and starting to develop an application, you should understand exactly what your goals are and how it's all going to work. Users can only access restricted pages once they've successfully logged in. A database holds all the user profiles—including the usernames and passwords—of all the registered users.
Users must register at the site before they can log in. More specifically, users must have a profile in the database. The database in this tutorial contains only one table, a users table, which contains a half dozen or so profiles. To register, users fill out a web form, which inserts their registration information, including a username and password, into the database, thus creating the profile. In the event that a user chooses an already existing username, the registration fails, and redirects the user to a page that tells him that the name isn't available. Once registered, a user can log in.
To log in, a user supplies a username and password combination, again in a web form. ASP, ColdFusion, or PHP queries the database to see if any records contain both the username and the password together. If it does, the log-in is successful, and the application flags the user as having logged in successfully (more on that in a moment). Once flagged, the user can access any number of restricted pages; that is, a user only has to log in once per site. If there are no records with both the username and password, the log-on fails, and the application redirects the user to a page that indicates that the log-on failed.
Once logged in, users can also log out by clicking a link. Once logged out, the application redirects them to a page that indicates their logged out state.
The following diagram shows the layout of the site relative to this login framework. Solid lines represent the movement of the user through the site. Dashed lines represent the exchange of data between pages and the database.
Figure 1. The login framework
Now that you understand the basics of the framework, you might wonder how the pages with restricted access determine whether the user logged in, and therefore whether to display the restricted content. Each restricted page has a script at the top that verifies whether the user logged in successfully, and if so, processes and displays the page. If the user has not logged in, the application typically redirect the user to a page that enables log-on; the restricted page never loads.
Introducing Sessions and Session Variables
The tricky part in the user authentication framework is how to flag a user across all website pages as logged in or not logged in, especially given your knowledge that the server forgets users and all their data in between every page request. In some cases, you may have overcome the server's forgetfulness by sending URL (or query string) and form variables between pages; this is a core capability of ASP, ColdFusion, and PHP. But these solutions are temporary, requiring you to manually send data to every page that needs it. It is better to use something more persistent.
One type of persistent variable is the cookie. A cookie is a name-value pair stored on the user's hard drive and sent to the server when the user makes an HTTP request. Using this technique, you can simulate the effect of the server remembering a user across multiple pages, simply by having pages use and respond to cookie data.
In large part to facilitate applications that need to keep track of users and data over time, ASP, ColdFusion, and PHP have special built-in features that handle much of this work for you. One of these is the session variable scope. Session variables contain information for a single user in a single session. If the user leaves the site or closes the browser for a period of time (usually about 20 minutes), then the session ends, and the application flushes the information from the server's memory.
The session variable is perfect for handling the login flag. That is, once a user successfully logs in, the application sets a session variable indicating the successful log-on. Each page that restricts access needs merely to check for the presence of this session variable to determine whether to grant access to the page or redirect the user to a different page.
For the data to be persistent, you must store it somewhere. You typically store session variables as cookies on the user's computer and match them to temporary session variables stored on the server. The storage of data in two locations and its subsequent matching is usually invisible to the developer; that is, while you may set and retrieve session variables, for example, you won't be both setting and retrieving server and cookie variables, because that happens behind the scenes.
From even this brief overview, you can understand why a session management framework is so important to authentication. It enables a single entry through a login page to provide access to multiple pages, without requiring the developer to manually create scripts that send the data from each page to the next.
Implementing Registration
Log-in presupposes a collection of valid usernames and passwords in the database. One way to get those combinations into the database is to create a registration form that inserts them there. I have created the form for you: It's in the exercise files, called registration.asp, registration.cfm, or registration.php (henceforth, I won't spell out all the extensions, but will only refer to ASP).
-
Open registration.asp in Dreamweaver.
I have already created the web form.
-
Take a moment to click each of the form elements and find out their names in the Property inspector.
Each item entered into a form field is stored as a variable using the name of the field. The first form field is the firstName field. If you type Jeffrey into the field and submit the form, the page submits a piece of data,
firstName=Jeffrey. -
Click the hidden form field (the yellow icon) in the lower-left corner of the form. In the Property inspector, name it userGroup and give it a value of visitor.
Figure 2. The hidden form field as shown in the Property inspector
Sometimes, you will need to pass data in a form that you don't want to collect from—or even provide access to—the user. This is one such situation. This user authentication framework will use roles-based authorization. Specifically, any registered user will be able to access some, but not all of the pages in the site. Some of the pages are restricted so that only special registered users can access them (think of admin pages, for example). One of the fields in the users table of the database is userGroup, which specifies whether the user has basic or full access to the site.
Obviously, you don't want to let the users determine whether they should have basic or full access. By creating this hidden field, you assign everyone to the basic group by default. An administrator will have to manually upgrade a given user's status, if she should be in the full-access group.
The form is now ready; it's time to add the script.
-
Click the Submit button. In the Server Behaviors panel, click the New Server Behavior (+) button, and choose Insert Record.
The Insert Record dialog box appears.
The Insert Record server behavior enables you to capture data from a web form and insert it as a new record in a given database table.
-
In the Insert Record dialog box, choose user_auth as the Connection (or whatever you named your database connection). Verify that you selected tbl_users in the Insert Into Table field. In the After Inserting Go To field, enter login.asp. Accept the rest of the defaults and click OK.
Figure 3. The Insert Record dialog box
The lower half of the dialog box enables you to specify which form data your application should insert into which database field; it is like a matching game. For example, you want the data from the firstName web form field to go into the firstName column in the database. If—as is the case here—you name the form fields the same as the database fields, Dreamweaver guesses by default that they are a match, and therefore, you don't have to manually specify each one.
With this server behavior in place, you have made it possible for users to create new profiles. However, you have not taken into account that two users might create profiles under the same username; you want to make this impossible.
-
Click to select the Submit button again. In the Server Behaviors panel, click the New Server Behavior (+) button, and choose User Authentication > Check New Username.
The Check New Username dialog box appears.
-
In the Check New Username dialog box, select username (or FORM.username, as ColdFusion is likely to display it) from the Username field pop-up menu and type registration_failed.asp in the If Already Exists, Go To field. Click OK.
Figure 4. The Check New Username dialog box
Since you asked for the user's e-mail address to use as their username, this shouldn't be a problem for legitimate users.
Whenever you create a form, make sure you deploy some sort of form validation, whether it's a client-side JavaScript behavior or a server-side script. In this case, I have already added a Validate Form behavior (a regular JavaScript behavior found in the Behaviors, not Server Behaviors, panel) to fulfill this function.
-
Save and if necessary, upload, register.asp. Close the file.
If you like, you can test this component of the site now or you can wait until you have added the login component.
Implementing a Log-on
Now that your registration page functions, you can build the login page. Remember, the role of the login page is to obtain (through a form) the user's username and password. Then, it will compare these values with the records in tbl_users. If there's a match, the login script sets a session variable indicating that the user is logged in. If there is no match, the user is redirected to a login failed page.
-
Open and explore login.asp.
Like registration.asp, this page contains a web form. However, this web form has only two fields—one for username and one for password.
-
Click to select the Submit button, and use the Server Behaviors panel to begin adding a User Authentication > Log In User behavior.
This behavior will do all the work of both verifying that the user's credentials match a pair in the database; that a session variable will be set, if the log-on was successful; and that the user will be redirected to an appropriate location, based on whether the log-on was successful.
-
In the top quarter of the Log In User dialog box, verify that frm_login is the selected form, that username is set as the Username Field, and that pwd is set as the Password field. In the second quarter of the dialog box, choose user_auth as the Connection, tbl_users as the Table, username as the Username Column, and pwd as the Password Column.
With these settings, you provide parameters that the script needs to compare the authentication entered into the login form with the list of registered users in the database.
-
In the third quarter of the Log In User dialog box, enter secret.asp for the successful login redirection, and login_failed.asp for the failed login redirection. Ensure that Go To Previous URL is checked. In the fourth quarter of the dialog box, select Username, Password, and Access Level, and choose userGroup in the Get Level From menu. Click OK.
In this step, you are accomplishing two goals. First, you are specifying where the user should be redirected depending on the success or failure of the log-on.
The Go To Previous URL setting needs some explanation. There are two ways that users will access this login page. First, they can access it directly by following the Log In link on the homepage. But they'll also see this page if they try to access a page that requires log-on (such as secret.asp), and they haven't logged in yet. That is, the login page may intercept their progress in the site. Upon successful log-on, users won't want to be redirected to the homepage—not when they were requesting secret.asp. By checking this option, you add functionality to the script that ensures that once these users have logged in, they are redirected to the page they attempted to load before they logged in.
The second goal you are accomplishing is to create the separate user group functionality discussed earlier. This will enable you to distinguish between basic access users and full access users who have logged in. Since these access levels are stored in the userGroup field of tbl_users, you specify that information in the Get Level From menu.
Figure 5. The Log In User dialog box
-
Click the Submit button. In the Behaviors panel, click the New Behavior (+) button and add a Form Validation behavior that makes both fields required.
Figure 6. The Validate Form dialog box
Every form needs some mechanism for validation.
-
Save and upload the page.
ASP and PHP users are ready to test the registration and login functionalities. To do so, open register.asp, and create a profile. Then log in with any e-mail address as a username and password. As always, try to break the application as well. Register the same name twice. Try logging in with the wrong password, try typing your phone number instead of your e-mail address, and so on.
Figure 7. The Site Registration page
ColdFusion users have a quick chore to do before they can test the application: They need to create the Application.cfm file that governs the web application framework. ASP users don't have to worry about creating a global.asa file—ASP will handle session management just fine without it. Likewise, PHP should handle session management without further coding.
Enabling Sessions With Application.cfm (ColdFusion Only)
One of the functions of the Log In User server behavior is that it creates a session variable when the user successfully logs in. The problem is, the session scope is inactive by default in ColdFusion, which means that the login page won't work. You'll have to activate session management in the ColdFusion Web Application Framework. Doing so is a simple matter of creating a new file (Application.cfm), and entering a single line of code.
-
Create a new page in code view. Delete all of the code on the page, including any HTML, XML, or other tags or code.
Application.cfm is not a regular web page, and so it should not have any code on it to begin.
-
Type the following code:
<cfapplication sessionmanagement="yes" setclientcookies="yes" name="user_auth" sessiontimeout="#CreateTimeSpan(0,0, 20, 0)#">
Figure 8. Enabling sessions with the Application.cfm file
The
cfapplicationtag effectively creates an application and enables the web application framework. It has several attributes, many of which are optional. One required attribute isname, which is any name you want to give your application. The other attributes used enable session management, enable the setting of cookies, and create a session timeout.Note that rather than specifying a simple period of time in the
sessiontimeoutattribute, there is a function,CreateTimeSpan(). This function takes four parameters, standing for days, hours, minutes, and seconds. Thus, thesessiontimeoutattribute is set for 20 minutes. In other words, if a user is inactive or leaves the site to browse on other pages for more than 20 minutes, all session variables associated with that user are flushed. In practical terms, it means the user would have to log in again. -
Save, close, and upload Application.cfm.
At this point you can test the registration and login features you've added in this lesson. As mentioned earlier, try to break the application, by entering every variation you can think of.
Restricting Access to Pages
By now, you have tested your registration and login pages, and they should work as expected. The only thing is, until you implement page restriction features to the pages you want to block access to, your registration and login framework is not very useful. In this task, you will add the server behaviors that prevent users from accessing pages, unless they've first logged in.
-
Back in Dreamweaver, open secret.asp.
This is one of the pages that users must log in to see.
-
Click anywhere on the page. In the Server Behaviors panel, insert a User Authentication > Restrict Access to Page server behavior. In the Restrict Based On group, choose Username, Password, and Access Level.
This dialog box not only lets you restrict access to the page; it also lets you restrict access to page based on a user's access level.
Of course, since no such levels are defined in the Select Level(s) area, you must define some.
Figure 9. The Restrict Access To Page dialog box
-
Click the Define button. In the Define Access Levels dialog box, place the cursor in the Name field, type visitor, and press the + button. Repeat the process to add admin. Click OK.
Dreamweaver won't check to make sure these groups actually exist; it takes your word for it, so make sure you spell them correctly. These correspond to the available values in the userGroup field of tbl_users. Once Dreamweaver knows the users' names, Dreamweaver can grant access to pages to users in either or both groups, and deny access to users not in either.
Figure 10. The Define Access Levels dialog box
-
Back in the Restrict Access to Page dialog box, Ctrl-click (Windows) or Command-click (Macintosh) to select both visitor and admin from the Select Level(s) area. In the If Access Denied, Go To field, enter login.asp. Click OK.
Figure 11. The Restrict Access To Page dialog box
You've done two things in this step. You've granted access to the page to users in either the visitor or admin group. Had you wanted to grant access to this page to only one of those groups, you would have selected only the one group. Once you've created the admin section of the site, you'll use this dialog box and to permit only members of the admin group.
The other thing you've done is redirect the user to login.asp if access is denied. This is how that interception described earlier happens. A user tries to access a restricted page without logging in, and she or he sees the login dialog box. Once log-on is achieved, the restricted page she or he was trying to access appears.
-
Repeat steps 1-4 for top_secret.asp, except grant access to top_secret.asp only to users in the admin group.
This page now requires authentication as well.
-
Save and upload all of the pages you have worked on in this lesson. Starting from the homepage (index.asp), try directly accessing secret.asp or top_secret.asp.
The authentication framework is fully functional. If you try to access a protected page, the login screen will appear. If you've created a registration account, use it. Or, remember you can use username: osiris@allectomedia.com and password: osiris to test. Once you've logged in, the application will automatically redirect you to the page you first requested.
The log-on that you created yourself should let you into secret.asp, but not top_secret.asp. Only admin users can access that page. On the login page, try the following credentials to get into top_secret.asp.
zfrome@starknet.com
hypochondriacNote: PHP users with PHP 4.2 and higher will be disappointed to learn that instead of being redirected to the originally requested page after log-on, the application sends them to the home page. The reason for this is that the server behavior that is supposed to cause the redirection to the originally requested page relies on a configuration setting, register_globals, that must be on for redirection. Since PHP 4.2, the default setting for register_globals is off. You can go into your php.ini file and change it to on and the site will work as expected. However, it was turned off for a reason—this setting creates a potential security hole in PHP. Thus, before you decide to go into php.ini and change the setting, I recommend that you research the issue on the web.
Implementing Log Out
Users may also want to log out. For example, imagine your site had confidential financial information, or other personal information. Enabling log out is easy in Dreamweaver, though users often need to close their browsers in addition to logging out to fully kill the session.
-
Back in Dreamweaver, open secret.asp.
This page already has some text on it about logging out, but it is not yet functional.
-
Drag to select the words log out. Add a User Authentication > Log Out User server behavior.
Figure 12. The access denied page in the browser
The Log Out User dialog box opens.
-
In the Log Out User dialog box, verify that Link Clicked “Log Out” is selected in the Log Out When category. In the When Done Go To field, type logout.asp.
Figure 13. The Log Out User dialog box
Clicking this link redirects the user to logout.asp, and it also removes the current session from the server's memory.
Unfortunately, since browsers often remember (the proper term is “cache”) the contents of recently visited pages, it is often possible for the user to press the Back button and access sensitive content again, even after logging out. Therefore, the user should also close the browser. Logging out and closing the browser ultimately ends the session. A note has been added to this effect on logout.asp.
-
Repeat steps 1-3 with top_secret.asp.
The login framework is now completely functional, from beginning to end. You can add as many pages as you want and restrict them by role as appropriate.
About the author
Jeffrey Bardzell is an IT trainer, curriculum developer, and multimedia instructional designer in the IT Training and Education ( http://ittraining.iu.edu/) department within University Information Technology Services at Indiana University, where he is also a Ph.D. Candidate in Comparative Literature.
He has authored numerous computer books, including Macromedia MX eLearning: Advanced Training From the Source (Macromedia Press); Special Edition Using Fireworks MX (Que); Macromedia Dreamweaver MX Dynamic Applications: Advanced Training From the Source (Macromedia Press). He also co-authored Mastering Macromedia Contribute (Wiley & Sons) and Fireworks 4 Expert Edge (Osborne).
Jeffrey is also a co-founder of Phireworx (http://www.phireworx.com), and he is a regular participant in Macromedia forums.